import os

import requests
from config import *


def get_cookie():
    return open("cookie.txt", "r", encoding="UTF-8").read()


def get_base64_code(file_path):
    return open(file_path, "r", encoding="UTF-8").read()


cookie = get_cookie()

id_list = []

csid = input("CSID: ")
start_id = input("Start id: ")
req = requests.post("https://note.leke.cn/auth/pc/note/ajax/getNoteRecord.htm", headers={
    "Cookie": cookie,
    "User-Agent": user_agent},
                    data={
                        "noteCsId": csid
                    })
print("Record Response:\n" + req.text)
is_start = False
for data in req.json()["datas"]["noteRecord"]:
    if data["noteRecordId"] == start_id or is_start:
        is_start = True
        id_list.append(data['noteRecordId'])
print("ID list:",id_list)
for i in os.listdir(folder):
    if len(id_list) == 0:
        print("ID list empty.")
        break
    file_path = folder + "/" + i
    raw_file_content = open("uploaded-music.txt", "r", encoding="UTF-8").read()
    # if input("Will upload this music: " + file_path + "\nConfirm? Y/N:") != "Y":
    #     exit(0)
    print("Now upload:", file_path)
    if file_path in raw_file_content:
        temp = input("Are you sure to upload a same audio? Y/N:")
        if temp != "Y":
            continue
    record_id = id_list[0]
    del id_list[0]
    # record_id = input("Input record ID:")
    req = requests.post("https://note.leke.cn/auth/global/fs/upload/audio/base64.htm", headers={
        "Cookie": cookie,
        "Host": "note.leke.cn",
        "User-Agent": user_agent},
                        data={
                            "file": get_base64_code(file_path),
                            "ext": "mp3",
                            "type": "audio"
                        })
    print("Response 1:\n" + req.text)
    response_object = req.json()
    if response_object["success"]:
        with open("uploaded-music.txt", "w", encoding="UTF-8") as fobj:
            fobj.write(raw_file_content + "\n" + file_path + " " + response_object["datas"]["url"])
        name = file_path.split("/")[-1].replace(".txt", "")
        edit_audio_req = requests.post("https://note.leke.cn/auth/pc/note/ajax/noteRecordEdit.htm", headers={
            "Cookie": cookie,
            "Host": "note.leke.cn",
            "User-Agent": user_agent},
                                       data={
                                           "noteRecordId": record_id,
                                           "audioUrl": response_object["datas"]["url"],
                                           "content": name,
                                           "isImportant": False
                                       })
        print("Response 2:\n" + edit_audio_req.text)
        os.remove(file_path)
    else:
        print("There was something wrong in request 1.")
